<?php

/*
 * This will be the Create Department page. 
 * 
 * Created by: Noan Babao
 * Date created: November 28, 2011
 */



    include("siteTop.php"); 
    include('includes/siteConfig.php'); 

    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
      // IDENTIFIES THE ACCOUNT DETAILS
   $userId = $_POST['userId'];
    $query = 
        "
            SELECT *
            FROM Account
            WHERE userId = '$userId'
        ";
    
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    $row = mysql_fetch_array($result);
    
    $accountUsername = $row['username'];
    $accountPassword = $row['password'];
    $accountLastName = $row['lastName'];
    $accountFirstName = $row['firstName'];
    $accountMiddleName = $row['middleName'];
    $accountStatus = $row['status'];
    $accountSecretQuestion = $row['secretQuestion'];
    $accountSecretAnswer = $row['secretAnswer'];
    
    $getDeptPos = " 
                     SELECT *
                     FROM Account_Dept_Pos
                     WHERE userId = '$userId'
                  ";
    $result = mysql_query($getDeptPos) or die ('Error in query: $getDeptPos. ' . mysql_error());
    $row = mysql_fetch_array($result);
    $x=0;
    while ($row = mysql_fetch_array($result)) {
            $deptPos[$x] = $row['deptPosId'];
            $x++;
        }
    $MAXdeptPos = $x;
    
?>

<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>
    
    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
        jQuery(document).ready(function(){ 
          
           getUserDepPos();
          
          

          jQuery("#addPosition").click(function(){
             getDepartments();
          });
          
          jQuery(".removeButton").live("click", function(){
            
             jQuery(this).parent().parent().remove();
             
             if(jQuery("#tableFooter").prev().attr('id') == "tableHeader")
                 {
                     getDepartments();
                 }
             
          });
           
           
          jQuery(".username").blur(function(){
          
             jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/admCheckUsername.php',
                    dataType : 'json',
                    data: {
                            username : jQuery(".username").val()
                    },
                    success : function(data){
                        if(!data)
                        {
                            alert("This Account already exists.");
                            jQuery(".username").val("");
                            jQuery(".username").focus();
                        }
                        
                    },
                    error : function() {
                        alert("fail ajax getdepartmentList.php");
                    }
             }); 
          });
           
          
          jQuery("#saveButton").click(function(){
            flag=1;
            jQuery(".required").each( function(){
                if(this.value==""){
                    flag=0;
                }
                
               
                    
                    
            });
            
            if(flag){
                jQuery(".deptPos").each(function(){
                    flag=0;
                    firstPosition = this.value;
                    
                    jQuery(".deptPos").each(function(){
                        secondPosition = this.value;
                        
                        if(firstPosition == secondPosition){
                            flag++;
                        }
                    });
                    if(flag>1){
                        alert("You can't have same Positions");
                        return false;
                    }
                    
                });
                
                
                if(flag<2){
                    if(jQuery("#password").val()!=jQuery("#password2").val()){
                        alert("Passwords does not match");
                        
                        jQuery("#password2").val("");
                        jQuery("#password").val("");
                        jQuery("#password").focus();
                    }
                    else{
                        
                    
                        position = "";
                        jQuery(".deptPos").each(function(){
                            position = this.value + "," + position ;
                        });

                          jQuery.ajax({
                                type : 'POST',
                                url : 'ajaxRequests/admEditAccount.php',
                                dataType : 'json',
                                data: {
                                       username : <?php echo $accountUsername; ?> ,
                                       password : jQuery("#password").val() ,
                                       firstName : jQuery("#fName").val() ,
                                       middleName : jQuery("#mName").val() ,
                                       lastName : jQuery("#lName").val() ,
                                       position : position,
                                       secretQuestion: jQuery("#secretQuestion").val(),
                                       secretAnswer: jQuery("#secretAnswer").val()
                                },
                                success : function(data){
                                    if(!flag){
                                        alert("fail in creating accountdeptpos");
                                    }else{

                                        jQuery("#tableFooter").append("<input type='hidden' name='accSuccessMessage' value='Successfully Updated an Account with employeeID <?php echo $accountUsername?>.'> ");
                                        jQuery("#formAccount").submit();
                                    }



                                },
                                error : function() {
                                    alert("fail ajax editaccount.php");
                                }
                         }); 
                     }
                }

            }
            else{
                alert("Please fill up all information.");
            }
            
          });
           
           
        }); // end document ready
        function getUserDepPos(){
             jQuery.ajax({
                type : 'POST',
                url : 'ajaxRequests/admGetUserPosition.php',
                dataType : 'json',
                async:false ,
                data: {
                    accountUserId : "<?php echo $userId; ?>"
                },
                success : function(data){
                  if (data) {
                      
                    // PUT POSITIONS TO TABLE POSITION
                    jQuery.each(data, function(index, data) {
                        if(data.status=='Active')
                        {
                            getDepartments();
                            jQuery("#tableFooter").prev().children(":first-child").children(":first-child").val(data.deptPosId);
                        }
                    });
                  }                  
                },
                error : function() {
                    alert("fail in AJAX [admGetUserPosition.php]");
                }
            }); // [END] GET ALL POSITION/S OF USER
            
        
        }
        
        function getDepartments()
        {
             jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/admGetDeptPos.php',
                    dataType : 'json',
                    async:false ,
                    data: {
                        departmentId : "All" ,
                        positionId : "All"
                    },
                    success : function(data){
                        jQuery("#tableFooter").before("<tr> <td> <select class='deptPos' name='deptPos'></select> </td>  <td align='center'><img src='images/ximage.png' height='20px' width='20px' style='cursor: pointer;'class='removeButton'/> </td>   </tr>");
                        
                        jQuery.each(data, function(index, data) {
                           jQuery("#tableFooter").prev().children(":first-child").children(":first-child").append("<option value='"+data.deptPosId+"'>"+data.departmentName+" - "+data.positionName+ " </option>");
                        });
                        
                       
                    },
                    error : function() {
                        alert("fail ajax admGetDeptPos.php");
                    }
             });
        }//end funtion getdepartment;
        
       
    </script>
<!-- HEAD END -->

<div id="content">
<h1>Edit Account</h1>
    <div class="contentbox">       
        <?php
        // Check permission
        $thePermissions = array('ACCSTP');
        if ( checkPermission( $thePermissions, $_SESSION['loggedUserId'] ) == true ) {
        ?>
            <span class="screenlet" >Account Information</span>
            <form id="formAccount" name="formAccount" action="admAccountSetup.php" method="Post" > 
                <table style="text-align:right;">
                    <tr>
                        <td > Employee ID : </td>
                        <td style="text-align:left">
                            <?php echo $accountUsername; ?> 
                        </td>
                    </tr>
                    
                    <tr>
                        <td>Password : </td>
                        <td>
                            <input style="float:left" type="password" class="required" value="<?php echo $accountPassword;?>" name="password" id="password" />
                        </td>
                    </tr>
                       <tr>
                        <td>Retype Password : </td>
                        <td>
                            <input style="float:left" type="password" class="required" value="<?php echo $accountPassword;?>" name="password2" id="password2" />
                        </td>
                    </tr>
                    <tr>
                        <td>First Name : </td>
                        <td>
                            <input style="float:left" type="text" class="required" value="<?php echo $accountFirstName;?>" name="fName" id="fName" />
                        </td>
                    </tr>
                    <tr>
                        <td>Middle Name : </td>
                        <td>
                            <input  style="float:left" type="text" class="required" value="<?php echo $accountMiddleName;?>" name="mName" id="mName" />
                        </td>
                    </tr>
                    <tr>
                        <td>Last Name : </td>
                        <td>
                            <input style="float:left" type="text" class="required" value="<?php echo $accountLastName;?>" name="lName" id="lName" />
                        </td>
                    </tr>
                      <tr>
                      
                        <td colspan="2" style="text-align:left;"> <br> <hr><i>In case you forget your password.</i> <br> <br> </td>
                        
                    </tr>
                    <tr>
                        <td>Secret Question: </td>
                        <td>
                            <input style="float:left" type="text" class="required" value="<?php echo $accountSecretQuestion;?>" name="secretQuestion" id="secretQuestion" />
                        </td>
                    </tr>
                    <tr>
                        <td>Secret Answer : </td>
                        <td>
                            <input style="float:left" type="text" class="required" value="<?php echo $accountSecretAnswer;?>" name="secretAnswer" id="secretAnswer" />
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2"><br><hr><br></td>
                    </tr>    
                        
                    <tr>
                        
                        <td colspan ="2">
                           
                        <table style="border-top-width: 1; border-top-color:gray" border="1">
                            <tr id="tableHeader">
                                
                                <th>
                                    Position
                                </th>
                                <th>
                                    Action
                                </th>
                            </tr>

                            <tr id="tableFooter">
                                <td>
                                </td>                               
                                <td align='center'>
                                    <input type="button" id="addPosition" value="Add" class="siteGreenButton">
                                </td>

                            </tr>

                        </table>  
                        </td>
                    </tr>
                
                </table>
                
                
                
                
                <input type="button" value="Save" id="saveButton" class="siteGreenButton">
                <input type="submit" value="Cancel" id="cancelButton" class="siteRedButton">
            </form>
        <?php
        }
        else {
            echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
        }
        // End checking permission
        ?>
    </div> <!-- contentbox end div -->
    <div style="position:relative; visibility: hidden">end</div>    <!-- extra space for contentbox -->
</div> <!-- content end div -->
<?php
    include ("siteBottom.php"); 
?>

